<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add_l">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in people" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td v-if="people.index !== 0">
            <button @click="delete_l(index)">删除</button>
            <button @click="update_l(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      people: [
        {
          id: 1,
          name: "张三",
          age: 17,
          sex: "男",
        },
        {
          id: 2,
          name: "李四",
          age: 27,
          sex: "男",
        },
        {
          id: 3,
          name: "王五",
          age: 36,
          sex: "男",
        },
        {
          id: 4,
          name: "赵六",
          age: 49,
          sex: "女",
        },
      ],
      name: "",
      age: "",
      sex: "男",
      id: "",
    };
  },
  methods: {
    // 添加 / 删除
    add_l() {
      if (this.name === "" || this.age === "") {
        alert("您还有未填项，不可提交！");
        return;
      }

      const number = parseInt(this.id); // 获取修改已有对象的id

      // 若对象未被添加过
      if (Object.is(number, NaN)) {
        this.people.push({
          id: this.people.length + 1,
          name: this.name,
          age: this.age,
          sex: this.sex,
        });

        return;
      }

      // 若对象在数组中已存在
      const index = number - 1; // 获取源对象索引
      this.people[index].name = this.name;
      this.people[index].age = this.age;
      this.people[index].sex = this.sex;
      return;
    },
    // 修改
    update_l(index) {
      this.name = this.people[index].name;
      this.age = this.people[index].age;
      this.sex = this.people[index].sex;
      this.id = this.people[index].id;
    },
    // 删除
    delete_l(index) {
      this.people.splice(index, 1);
    },
  },
};
</script>